package com.toutou.base.util

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

class SingleLiveEvent<T> : MutableLiveData<T>() {
    private val pending = AtomicBoolean(false)

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, Observer { t ->
            if (pending.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        })
    }

    override fun setValue(t: T?) {
        pending.set(true)
        super.setValue(t)
    }

    // 使用postValue确保线程安全
    override fun postValue(t: T?) {
        pending.set(true)
        super.postValue(t)
    }

    // 避免直接调用call方法
    fun call() {
        value = null
        reset()
    }

    fun reset() {
        pending.set(false)
    }
}